package cn.stylefeng.guns.modular.single.service.impl;

import cn.hutool.Hutool;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.stylefeng.guns.modular.single.Param.PatientEscalationParam;
import cn.stylefeng.guns.modular.single.Param.PatientParam;
import cn.stylefeng.guns.modular.single.entity.Patient;
import cn.stylefeng.guns.modular.single.entity.PatientEscalation;
import cn.stylefeng.guns.modular.single.mapper.PatientDAO;
import cn.stylefeng.guns.modular.single.mapper.PatientEscalationDAO;
import cn.stylefeng.guns.modular.single.service.PatientEscalationService;
import cn.stylefeng.roses.kernel.auth.api.context.LoginContext;
import cn.stylefeng.roses.kernel.db.api.factory.PageFactory;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.event.api.annotation.BusinessListener;
import cn.stylefeng.roses.kernel.log.requestapi.entity.SysLog;
import cn.stylefeng.roses.kernel.log.requestapi.mapper.SysLogMapper;
import cn.stylefeng.roses.kernel.rule.annotation.ApiLog;
import cn.stylefeng.roses.kernel.rule.annotation.BizLog;
import cn.stylefeng.roses.kernel.sys.modular.user.entity.SysUserOrg;
import cn.stylefeng.roses.kernel.sys.modular.user.mapper.SysUserMapper;
import cn.stylefeng.roses.kernel.sys.modular.user.mapper.SysUserOrgMapper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class PatientEscalationServiceImpl  extends ServiceImpl<PatientEscalationDAO, PatientEscalation> implements PatientEscalationService {
    @Value("${inner.url}")
    private String url;
    @Resource
    private PatientEscalationDAO patientEscalationDao;
    @Resource
    private PatientDAO patientDao;

    @Resource
    private SysLogMapper sysLogMapper;
    public PageResult<PatientEscalation> findPage(PatientParam patientParam){

        LambdaQueryWrapper<PatientEscalation> wrapper = Wrappers.<PatientEscalation>lambdaQuery()
                .in(PatientEscalation::getStatus,2,3,5,-1);
        if(StrUtil.isNotBlank(patientParam.getName())){
            wrapper.like(PatientEscalation::getName,patientParam.getName());
        }
        if(StrUtil.isNotBlank(patientParam.getInNo())){
            wrapper.like(PatientEscalation::getInNo,patientParam.getInNo());
        }
        if(StrUtil.isNotBlank(patientParam.getDiseaseCode())){
            wrapper.eq(PatientEscalation::getDiseaseCode,patientParam.getDiseaseCode());
        }
        Page<PatientEscalation> page = (Page)this.page(PageFactory.defaultPage(), wrapper);
        return PageResultFactory.createPageResult(page);
    }

   public int save(PatientEscalationParam param) {
       Date escalationDate = null;
       if(param.getStatus() == 3){
            escalationDate = new Date();
           PatientEscalation patientEscalation =  patientEscalationDao.selectOne(
                   Wrappers.<PatientEscalation>lambdaQuery().eq(PatientEscalation::getInNo,param.getInNo()));
           if(patientEscalation==null){
               return 0;
           }
           param.setDiseaseCode(patientEscalation.getDiseaseCode());
           param.setDiseaseName(patientEscalation.getDiseaseName());
           JSONObject obj = JSON.parseObject(patientEscalation.getContent());
          post(obj,param);
       }
       int n = patientEscalationDao.update(null, Wrappers.<PatientEscalation>lambdaUpdate()
               .set(PatientEscalation::getStatus,param.getStatus())
               .set(PatientEscalation::getEscalationDate,escalationDate)
                .set(PatientEscalation::getReason,param.getReason())
               .eq(PatientEscalation::getInNo,param.getInNo()));
       n = n+ patientDao.update(null, Wrappers.<Patient>lambdaUpdate()
               .set(Patient::getStatus,param.getStatus())
               .set(Patient::getEscalationDate,escalationDate)
               .eq(Patient::getInNo,param.getInNo()));

       return n;
   }
    @BizLog
    private PatientEscalationParam post(JSONObject param1,PatientEscalationParam patient){
        String body = JSON.toJSONString(param1);
        SysLog log =new SysLog();
        log.setLogId(RandomUtil.randomLong());
        log.setLogContent(patient.getDiseaseName()+"上报");
        log.setAppName("single");
        log.setRequestUrl(url+patient.getDiseaseCode()+ "/1.2/put/");
        log.setRequestParams(body);
        Long userId = LoginContext.me().getLoginUser().getUserId();
        log.setUserId(userId);
        log.setCreateTime(new Date());
        log.setHttpMethod("POST");
        String rpcResult = "";
        try {
             rpcResult = HttpRequest.post(url+patient.getDiseaseCode()+ "/1.2/put/")
                    .body(body , "application/json")
                    .execute()
                    .body();
            JSONObject resp = JSON.parseObject(rpcResult);
            if(resp.getInteger("code")==1){
                log.setClientOs("Success");
                patient.setStatus(3);
            }else {
                log.setClientOs("Fail");
                patient.setStatus(-1);
                patient.setReason( resp.getString("message"));
            }
        }catch (Exception ex){
            rpcResult = ex.getMessage();
            log.setClientOs("Fail");
            patient.setStatus(-1);
            patient.setReason( ex.getMessage());
        }finally {
            log.setRequestResult(rpcResult);
            sysLogMapper.insert(log);
        }
       return  patient;
    }
}
